package dao

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type Users struct {
	Id        int       `json:"id" gorm:"primary_key" description:"自增主键"`
	Openid    string    `json:"openid" gorm:"column:openid" description:"openid"`
	Unionid   string    `json:"unionid" gorm:"column:unionid" description:"unionid"`
	Name      string    `json:"name" gorm:"column:name" description:"名称"`
	Appname   string    `json:"appname" gorm:"column:appname" description:"appname"`
	Avatar    string    `json:"avatar" gorm:"column:avatar" description:"头像"`
	Gender    int       `json:"gender" gorm:"column:gender" description:"性别"`
	Phone     string    `json:"phone" gorm:"column:phone" description:"手机号"`
	Shared    int       `json:"shared" gorm:"column:shared" description:"分享"`
	Left      int       `json:"left" gorm:"column:left" description:"剩余次数"`
	SelfId    string    `json:"self_id" gorm:"column:self_id" description:"self_id"`
	Fromwhere string    `json:"fromwhere" gorm:"column:fromwhere" description:"平台来自"`
	Brand     string    `json:"brand" gorm:"column:brand" description:"手机品牌"`
	Platform  string    `json:"platform" gorm:"column:platform" description:"平台"`
	CreatedAt time.Time `json:"created_at" gorm:"column:created_at" description:"创建时间"`
	UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at" description:"更新时间"`
	UpdatedIp string    `json:"updated_ip" gorm:"column:updated_ip" description:"更新IP"`
}

func (t *Users) TableName() string {
	return "edt_users"
}

func (t *Users) Find(c *gin.Context, tx *gorm.DB, where string, alias string) (*Users, error) {
	Users := &Users{}
	var err error
	if alias == "phone" {
		err = tx.WithContext(c).Where("phone = ?", where).First(Users).Error
	}
	if alias == "unionid" {
		err = tx.WithContext(c).Where("unionid = ?", where).First(Users).Error
	}
	if err != nil {
		return nil, err
	}
	return Users, nil
}

func (t *Users) Add(c *gin.Context, tx *gorm.DB, data *Users) (*Users, error) {
	err := tx.WithContext(c).Create(data).Error
	if err != nil {
		return data, err
	}
	return data, nil
}

func (t *Users) Update(c *gin.Context, tx *gorm.DB, SelfId string, UpdatedIp string) (*Users, error) {
	Users := &Users{}
	//times := time.Now().Format("2006-01-02 15:04:05")
	err := tx.WithContext(c).Model(Users).Where("self_id=?", SelfId).Update("updated_ip", UpdatedIp).Error
	if err != nil {
		return nil, err
	}
	return Users, nil
}
